package org.catpay.modules.sys.controller;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.catpay.common.annotation.SysLog;
import org.catpay.common.annotation.UpdateIgnore;
import org.catpay.common.utils.CommonMap;
import org.catpay.common.utils.Constant;
import org.catpay.common.utils.PageUtils;
import org.catpay.common.validator.group.AddGroup;
import org.catpay.common.validator.group.UnableGroup;
import org.catpay.common.validator.group.UpdateGroup;
import org.catpay.modules.sys.entity.SysRoleEntity;
import org.catpay.modules.sys.entity.SysUserEntity;
import org.catpay.modules.sys.entity.SysUserRoleEntity;
import org.catpay.modules.sys.form.PasswordForm;
import org.catpay.modules.sys.service.SysRoleService;
import org.catpay.modules.sys.service.SysUserRoleService;
import org.catpay.modules.sys.service.SysUserService;
import org.catpay.modules.sys.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;

import cn.hutool.core.collection.CollectionUtil;

/**
 * 系统用户
 * 
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends AbstractController {
	
	@Autowired
	private SysUserService sysUserService;
	
	@Autowired
	private SysUserRoleService sysUserRoleService;
	
	@Autowired
	private SysRoleService sysRoleService;

	/**
	 * 所有用户列表
	 */
	@PostMapping("/list")
	@RequiresPermissions("sys:user:list")
	public R<?> list(@RequestBody Map<String, Object> params){
		
		PageUtils page = sysUserService.queryPage(params);

		return R.ok(CommonMap.getMap().put("page", page));
	}
	
	/**
	 * 获取登录的用户信息
	 */
	@GetMapping("/info")
	public R<?> info(){
		SysUserEntity user = getUser();
		return R.ok(CommonMap.getMap().put("user", user));
	}
	
	/**
	 * 修改登录用户密码
	 */
	@SysLog("修改密码")
	@PostMapping("/password")
	public R<?> password(@RequestBody PasswordForm form){
		
		//sha256加密
		String password = new Sha256Hash(form.getPassword(), getUser().getSalt(),1024).toHex();
		//sha256加密
		String newPassword = new Sha256Hash(form.getNewPassword(), getUser().getSalt(),1024).toHex();
				
		//更新密码
		boolean flag = sysUserService.updatePassword(getUserId(), password, newPassword);
		if(!flag){
			return R.error("原密码不正确");
		}
		
		return R.ok();
	}
	
	/**
	 * 用户信息
	 */
	@GetMapping("/info/{userId}")
	@RequiresPermissions("sys:user:info")
	public R<?> info(@PathVariable("userId") Long userId){
		if(!isSupperAdmin() && sysUserRoleService.selectCount(new EntityWrapper<SysUserRoleEntity>()
				.eq("user_id", userId)
				.eq("role_id", Constant.ADMIN_GROUP)) > 0) {
			return R.error("超级管理员才能操作");
		}
		
		
		SysUserEntity user = sysUserService.selectById(userId);
		
		//获取用户所属的角色列表
		List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
		user.setRoleIdList(roleIdList);
		
		List<SysRoleEntity> roles = sysRoleService.selectList(new EntityWrapper<SysRoleEntity>().ne(!isSupperAdmin(),"role_id", Constant.ADMIN_GROUP));
		return R.ok(CommonMap.getMap().put("user", user).put("roles", roles));
	}
	
	/**
	 * 保存用户
	 */
	@SysLog("保存用户")
	@PostMapping("/save")
	@RequiresPermissions("sys:user:save")
	public R<?> save(@RequestBody @Validated({AddGroup.class}) SysUserEntity user){
		if(CollectionUtil.isNotEmpty(user.getRoleIdList())  && !isSupperAdmin()) {
			if(user.getRoleIdList().contains(Constant.ADMIN_GROUP)) {
				return R.error("非法操作");
			}
		}
		user.setCreateUserId(getUserId());
		sysUserService.save(user);
		
		return R.ok();
	}
	
	@PostMapping("/unable")
	@SysLog("停用用户")
	@UpdateIgnore(groups={UnableGroup.class})
	public R<?> unable(@RequestBody @Validated({UnableGroup.class}) @UpdateIgnore(groups={UnableGroup.class}) SysUserEntity user){
		if(user.getUserId() == Constant.SUPER_ADMIN) {
			return R.error("超级管理员不能停用");
		}
		if(!isSupperAdmin() && sysUserRoleService.selectCount(new EntityWrapper<SysUserRoleEntity>()
				.eq("user_id", user.getUserId())
				.eq("role_id", Constant.ADMIN_GROUP)) > 0) {
			return R.error("非超级管理员不能停用管理员");
		}
		sysUserService.updateById(user);
		return R.ok();
	}
	
	
	/**
	 * 修改用户
	 */
	@SysLog("修改用户")
	@PostMapping("/update")
	@RequiresPermissions("sys:user:update")
	@UpdateIgnore(groups={UpdateGroup.class})
	public R<?> update(@RequestBody @Validated({UpdateGroup.class}) @UpdateIgnore(groups={UpdateGroup.class}) SysUserEntity user){
		if(user.getUserId() == Constant.SUPER_ADMIN) {
			return R.error("超级管理员不能修改");
		}
		if(!isSupperAdmin() && sysUserRoleService.selectCount(new EntityWrapper<SysUserRoleEntity>()
				.eq("user_id", user.getUserId())
				.eq("role_id", Constant.ADMIN_GROUP)) > 0) {
			return R.error("非超级管理员不能修改管理员");
		}
		user.setCreateUserId(getUserId());
		sysUserService.update(user);
		
		return R.ok();
	}
	
	@SysLog("重置密码")
	@PostMapping("/resetPwd")
	public R<?> resetPwd(@RequestBody Long[] userIds){
		if(ArrayUtils.contains(userIds, 1L)){
			return R.error("超级管理员密码不能重置");
		}
		if(!isSupperAdmin() && sysUserRoleService.selectCount(new EntityWrapper<SysUserRoleEntity>()
				.in("user_id", userIds)
				.eq("role_id", Constant.ADMIN_GROUP)) > 0) {
			return R.error("非超级管理员不能重置管理员密码");
		}
		sysUserService.resetPwd(userIds);
		return R.ok();
	}
	
	
	/**
	 * 删除用户
	 */
	@SysLog("删除用户")
	@PostMapping("/delete")
	@RequiresPermissions("sys:user:delete")
	public R<?> delete(@RequestBody Long[] userIds){
		if(!isSupperAdmin()) {
			return R.error("只有超级管理员才能删除用户");
		}
		
		if(ArrayUtils.contains(userIds, 1L)){
			return R.error("超级管理员不能删除");
		}
		
		sysUserService.deleteBatch(userIds);
		
		return R.ok();
	}
}
